package
{
	import flash.events.*;
	import flash.net.*;
	import flash.utils.ByteArray;
	
	public class Net
	{
		//private static var bad:String = "BADSNARF";
		private static var loader:URLLoader = new URLLoader();
		loader.dataFormat = URLLoaderDataFormat.BINARY;
		loader.addEventListener(Event.COMPLETE, completeHandler);
		loader.addEventListener(Event.OPEN, openHandler);
		loader.addEventListener(ProgressEvent.PROGRESS, progressHandler);
		loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
		loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
		loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		public static var buffer:ByteArray;
		
		/* Store all snarfed files in static hash? */
		
		public static function Snarf(FileName:String):void {
			var request:URLRequest = new URLRequest(FileName);
			/* Load a file from SWF's local path */
            try {
                loader.load(request);
                debug("Snarfing File: " + FileName);
            } catch (error:Error) {
            	debug("Unable to Snarf File: " + FileName);
            	//Flow.Do(bad);
            	/* TODO: retry? quit? */
            }
		}
		
		/* what else: */ 
		/*   1)  either CopyToRAM() OR give RAM dest. addr. in constuctor arguments */
		/*   2)  TODO: allow gzipped ROM images - Broken under IE6? */
		/*   3)  TODO: checksums (should be part of ROM image format?) */
		
		private static function completeHandler(event:Event):void {
            var loader:URLLoader = URLLoader(event.target);
            /* do checksum? */
            //writeBytes(loader.data as ByteArray);
            buffer = (loader.data as ByteArray);
            //m1.debug.print("LOAD DONE");
            Flow.Next();
        }

        private static function openHandler(event:Event):void {
        	/* OK */
            //debug("openHandler: " + event);            
        }

        private static function progressHandler(event:ProgressEvent):void {
        	/* OK */
            //debug("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
            /* forward to system progress bar (displayed on boot) */            
        }

        private static function securityErrorHandler(event:SecurityErrorEvent):void {
        	/* Error */
            debug("securityErrorHandler: " + event);            
            //Flow.Do(bad);
        }

        private static function httpStatusHandler(event:HTTPStatusEvent):void {
        	/* OK */
            //debug("httpStatusHandler: " + event);
        }

        private static function ioErrorHandler(event:IOErrorEvent):void {
        	/* Error */
            debug("ioErrorHandler: " + event);
            /* should we retry? */
            //Flow.Do(bad);
        }
        
        private static function debug(msg:String):void {
        	m1.debug.print("NET: " + msg);
        }
	}
}